<template>
  <a-modal
    width="1000px"
    :visible="visible"
    title="发布公告"
    cancelText="取消"
    okText="提交"
    @ok="submit"
    @cancel="cancel"
  >
    <a-form
      ref="formRef"
      :model="formState"
      :label-col="labelCol"
      :wrapper-col="wrapperCol">
      <a-form-item ref="ebTitle" label="公告标题" name="ebTitle">
        <a-input v-model:value="formState.ebTitle"/>
      </a-form-item>
      <a-form-item ref="ebTitle" label="上传附件" name="ebTitle">
        <a-upload
          v-model:file-list="fileList"
          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"
          :headers="headers"
          :remove="removeAccessory"
          @change="handleChange">
          <a-button>
            <upload-outlined></upload-outlined>
            Upload
          </a-button>
        </a-upload>
      </a-form-item>
      <a-form-item label="展示封面" name="enable">
        <a-upload
          name="file"
          v-model="formState.ebCover"
          list-type="picture-card"
          class="avatar-uploader1"
          :show-upload-list="false"
          action="http://192.168.0.145:9292/api/sys/upload/uploadFiles"
          :before-upload="beforeUpload"
          @change="handleChange1"
          :headers="headers"
        >
          <img v-if="imageUrl1" :src="imageUrl1" alt="avatar" width="110" height="110"/>
          <div v-else>
            <loading-outlined v-if="loading"></loading-outlined>
            <plus-outlined v-else></plus-outlined>
            <div class="ant-upload-text">Upload</div>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="公告内容" name="ebContent">
        <BasicEditor v-if="show" ref="header"></BasicEditor>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script>
import {message} from 'ant-design-vue';
import {list} from "@/api/module/post";
import {save, uploadAvatar} from "@/api/module/user";
import {defineComponent, reactive, ref, toRaw} from "vue";
import {ebcSave, eicSave, tree} from "@/api/module/experiment";
import {PlusOutlined, LoadingOutlined} from '@ant-design/icons-vue';
import BasicEditor from "@/view/components/BasicEditor";

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

export default defineComponent({
  components: {
    LoadingOutlined,
    PlusOutlined,
    BasicEditor,
  },
  props: {
    visible: {
      type: Boolean,
    },
  },
  data() {
    return {
      show: true,
      showHtml: null,
    }
  },
  emit: ["close"],
  setup(props, context) {
    const loading = ref(false);
    const loading1 = ref(false);
    const imageUrl = ref('');
    const fileList = ref([]);
    const imageUrl1 = ref('');
    const formRef = ref();
    const header = ref(null);

    const state = reactive({
      posts: [],
      depts: [],
    })

    const formState = reactive({
      ebCover: "",
      accessoryList: [],
      objectList: [],
    });


    const submit = (e) => {
      formState.ebContent = toRaw(header.value.aaa)
      formState.ebCategory = 1
      formState.accessoryList = [];
      if (formState.objectList.length > 0) {
        for (let i = 0; i < formState.objectList.length; i++) {
          let objectListElement = formState.objectList[i];
          formState.accessoryList.push(objectListElement.response.data.url)
        }
      }
      formRef.value.validate().then(() => {
        ebcSave(toRaw(formState)).then((response) => {
          if (response.success) {
            message.success({content: '保存成功', duration: 1}).then(() => {
              cancel();
            });
          } else {
            message.error({content: '保存失败', duration: 1}).then(() => {
              cancel();
            });
          }
        })
      }).catch(error => {
        console.log('error', error);
      });
    };

    const cancel = (e) => {
      formRef.value.resetFields();
      context.emit("close", false);
    };


    const removeAccessory = (file) => {
      console.log("删除文件+", file.response.data.url)
      console.log("已经上传的文件列表：", formState.accessoryList)
    }

    const handleChange = ({
                            file,
                            fileList,
                          }) => {
      if (file.status !== 'uploading') {
        console.log("打印：", file.response.data.url)
        formState.objectList = JSON.parse(JSON.stringify(fileList))

        // let number = formState.accessoryList.indexOf(file.response.data.url);
        // if(number == -1){
        //   formState.accessoryList.push( file.response.data.url)
        //   // 说明这个数组集合中包含该链接
        //   // 删除掉
        //   formState.accessoryList.slice(number,1)
        // }
        console.log("集合：", JSON.parse(JSON.stringify(fileList)))
      }
    };
    // 上传头像改变时的状态
    const handleChange1 = info => {
      if (info.file.status === 'uploading') {
        loading1.value = true;
        return;
      }

      if (info.file.status === 'done') {
        getBase64(info.file.originFileObj, base64Url => {
          imageUrl1.value = base64Url;
          loading1.value = false;
          console.log("图片1url：", info.file.response.data.url)
          if (info.file.response.code === 200) {
            formState.ebCover = info.file.response.data.url
            message.success("上传成功")
          }
        });
      }

      if (info.file.status === 'error') {
        loading1.value = false;
        message.error('upload error');
      }
    };
    // 上传文件之前的钩子
    const beforeUpload = file => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJpgOrPng) {
        message.error('只能上传【png/jpg】格式图片！');
      }
      const isLt2M = file.size / 1024 / 1024 < 100;
      if (!isLt2M) {
        message.error('图片大小不能超过【100MB】!');
      }
      return isJpgOrPng && isLt2M;
    };
    // 上传图片携带token
    const tokenKey = localStorage.getItem("token_key");
    const token = localStorage.getItem("token")

    const headers = {
      "Authorization": token,
      "Authorization-key": tokenKey
    };

    return {
      state,
      submit,
      cancel,
      formRef,
      formState,

      labelCol: {span: 4},
      wrapperCol: {span: 26},

      replaceFields: {children: 'children', title: 'maName', key: 'id', value: 'id'},
      // 下面是上传图片所用接口
      loading1,
      imageUrl1,
      fileList,
      removeAccessory,
      handleChange,
      handleChange1,
      beforeUpload,
      headers,
      header,
    };


  },
});
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 100%;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
